package alingrad.engine.graphics;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.opengles.GL10;

import alingrad.engine.collisions.CollisionMaskData;
import alingrad.engine.util.GLColor;

public class Sprite extends RenderablePrimitive {

	private final Texture mTexture;

	private float[] mTextures;
	private FloatBuffer mTextureBuffer;

	public Sprite(final Texture texture) {
		super(false);
		mTexture = texture;
		final float halfWidth = texture.mWidth / 2;
		final float halfHeight = texture.mHeight / 2;
		mVertices = new float[12]; {
			mVertices[0] = -halfWidth;
			mVertices[1] = halfHeight;
			mVertices[2] = 0f;
			mVertices[3] = -halfWidth;
			mVertices[4] = -halfHeight;
			mVertices[5] = 0f;
			mVertices[6] = halfWidth;
			mVertices[7] = -halfHeight;
			mVertices[8] = 0f;
			mVertices[9] = halfWidth;
			mVertices[10] = halfHeight;
			mVertices[11] = 0f;
		}
		mIndices = new short[6]; {
			mIndices[0] = 0;
			mIndices[1] = 1;
			mIndices[2] = 2;
			mIndices[3] = 0;
			mIndices[4] = 2;
			mIndices[5] = 3;
		}
		mTextures = new float[8]; {
			mTextures[0] = 0f;
			mTextures[1] = 0f;
			mTextures[2] = 0f;
			mTextures[3] = 1f;
			mTextures[4] = 1f;
			mTextures[5] = 1f;
			mTextures[6] = 1f;
			mTextures[7] = 0f;
		}
		createBuffers();
	}

	@Override
	protected void createBuffers() {
		super.createBuffers();
		ByteBuffer tbb = ByteBuffer.allocateDirect(mTextures.length * 4);
		tbb.order(ByteOrder.nativeOrder());
		mTextureBuffer = tbb.asFloatBuffer();
		mTextureBuffer.put(mTextures);
		mTextureBuffer.position(0);
	}

	@Override
	public void draw(GL10 gl, final float x, final float y, final float rotation, final float scaleX,
			final float scaleY, final GLColor color) {
		gl.glPushMatrix(); {
			gl.glEnable(GL10.GL_TEXTURE_2D);
			gl.glColor4f(color.mRed, color.mGreen, color.mBlue, color.mAlpha);
			mTexture.bind(gl);
			gl.glTranslatef(x, y, 0);
			gl.glRotatef(rotation, 0, 0, 1);
			gl.glScalef(scaleX, scaleY, 1f);
			gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
			gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
			gl.glFrontFace(GL10.GL_CCW);
			gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer);
			gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTextureBuffer);
			gl.glDrawElements(GL10.GL_TRIANGLES, mIndices.length, GL10.GL_UNSIGNED_SHORT, mIndexBuffer);
			gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
			gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
		} gl.glPopMatrix();
	}

	@Override
	public CollisionMaskData getData() {
		return mTexture.mData;
	}

}
